package com.rinvay.asdownloader.platform.persistent;

import com.rinvay.utils.logger.Logger;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class FileDownloadHelper extends SQLiteOpenHelper
{
    private static final String TAG = "FileDownloadHelper";

    private static final String DATABASE_NAME = "downloadtask.db";
    private static final int DATABASE_VERSION = 1;

    public static final String TABLE_DOWNLOAD_TASK = "downloadtask";
    
    private static FileDownloadHelper helper;

    private FileDownloadHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    public void onCreate(SQLiteDatabase db) {
        String downloadtasktable = "create table " + TABLE_DOWNLOAD_TASK + " ("
                + DownloadTaskData._ID + " integer primary key, "
                + DownloadTaskData.KEY_UUID + " TEXT, "
                + DownloadTaskData.KEY_URL + " TEXT, "
                + DownloadTaskData.KEY_DIRECTORY + " TEXT, "
                + DownloadTaskData.KEY_FILE_NAME + " TEXT, "
                + DownloadTaskData.KEY_ISFINISHED + " TEXT, "
                + DownloadTaskData.KEY_SIZE + " integer, "
                + DownloadTaskData.KEY_CUR_LENGTH + " integer, "
                + DownloadTaskData.KEY_THREAD_SIZE + " integer, "
                + DownloadTaskData.KEY_PART_DATA + " TEXT"
                + " )";
        db.execSQL(downloadtasktable);
    }

    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        Logger.info(TAG, "upgrade database from version " + oldVersion + " to "
                + newVersion + ", which will which will destroy all old data");
        db.execSQL("drop table if exists " + TABLE_DOWNLOAD_TASK);
        onCreate(db);
    }
    
    public static synchronized FileDownloadHelper getInstance(Context ctx) {
        if(helper == null) {
            helper = new FileDownloadHelper(ctx.getApplicationContext());
        }
        return helper;
    }
    
}
